﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using Swift;
public class Factory : Port {

	public Game Game;

	Dictionary<string, GameObject> dict = new Dictionary<string, GameObject>();


	public Factory() {

		OnMessage ( "Add", (data)=>{
			int tid = data.ReadInt();                     // 种类
			string uid = data.ReadString();               // 唯一标识
			float x = data.ReadFloat();                   // 位置
			float y = data.ReadFloat();                     
			int f = data.ReadInt();                       // 方向
			string tag = data.ReadString();

			GameObject obj = Game.Create(tid, x, y, f);

			if(tid == 10) {
				if(tag.EndsWith("player1") || tag.EndsWith("player2")) {
					Game.ShotEffect(obj);
				}
			}

			if(obj != null) {
				dict.Add(uid, obj);
			} 

			if(21 <= tid && tid <= 26) {  			      // 食物
				Game.Flicker(obj);						  // 食物闪烁效果
			} 

		});

		OnMessage ("Remove", (data) => {

			int tid = data.ReadInt();
			string uid = data.ReadString();

			if(dict.ContainsKey(uid)) {

				GameObject obj = dict[uid];

				if(tid == 10){
					Game.BulletEffect(obj);
				} else if(100 < tid && tid < 1000) {
					Game.TankEffect(obj);
				}

				Game.Remove(obj);
				dict.Remove(uid);
			} else {
				throw new UnityException("uid = " + uid + " 不存在");
			}

		});

		OnMessage ("Repos", (data) => { 

			int tid = data.ReadInt();
			string uid = data.ReadString();
			float x = data.ReadFloat();
			float y = data.ReadFloat();
			int f = data.ReadInt();	
			int status = data.ReadInt();  				  // 状态

			if(dict.ContainsKey(uid)) {

				GameObject obj = dict[uid];

				Game.Repos(obj, x, y, f);

				if( (status & 16 ) > 0 ) {   			  // 携带食物
					Game.FlashRed(obj);
				} else {					
					Game.StopFlashRed(obj);
				}

				if( (status & 2) > 0) {  				  // 无敌
					Game.InvincibleEffect(obj);
				} else {
					Game.StopInvincibleEffect(obj);
				}

				if(100 < tid && tid < 300) {
					if( (status & 1) > 0 ) {			  // 玩家暂停（友方攻击惩罚）
						Game.Flicker(obj);
					} else {
						Game.StopFlicker(obj);
					}
 				}

			} else {
				throw new UnityException("uid = " + uid + " 不存在");
			}
		});

		OnMessage ("Refresh", (data) => {

			string uid = data.ReadString();
			int tid = data.ReadInt();
			float x = data.ReadFloat();
			float y = data.ReadFloat();
			int f = data.ReadInt();

			Game.Remove(dict[uid]);
			dict.Remove(uid);

			dict[uid]=Game.Create(tid, x, y, f);


		});


		OnMessage ("Status", (data) => {

			Game.chapter = data.ReadInt();
			Game.life1 = data.ReadInt();
			Game.life2 = data.ReadInt();
			Game.num = data.ReadInt();

		});

		OnMessage ("Balance", (data) => {

			int chapter = data.ReadInt();
			int maxChapter = data.ReadInt();
			bool pass = data.ReadInt() == 1;
			int[,] num = new int[4,2];
			for (int i=0; i<4; i++) {
				for (int j=0; j<2; j++) {
					num[i, j] = data.ReadInt();	
				}
			}

			Debug.Log(pass ? "赢了" : "输了");
			Game.Balance(chapter, maxChapter, pass, num);
		});

	}


}
